const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { authenticateToken, validateUser } = require('../middleware/auth');
const cryptoUtil = require('../utils/crypto');

// 生成JWT令牌
const generateToken = (openid) => {
    return jwt.sign(
        { openid },
        process.env.JWT_SECRET || JWT_SECRET,
        { expiresIn: '7d' }
    );
};

router.get('/encryption-key', authenticateToken, async (req, res) => {
    try {
        // 为每个用户生成唯一的加密密钥
        const userId = req.user.id;
        let encryptionKey = await getUserEncryptionKey(userId);

        if (!encryptionKey) {
            // 生成新的加密密钥
            encryptionKey = generateUserEncryptionKey(userId);
            await saveUserEncryptionKey(userId, encryptionKey);
        }

        res.json({
            success: true,
            data: {
                encryptionKey: encryptionKey
            }
        });
    } catch (error) {
        console.error('获取加密密钥失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

// 生成用户专属加密密钥
function generateUserEncryptionKey(userId) {
    const crypto = require('crypto');
    const serverSecret = process.env.MASTER_ENCRYPTION_KEY;

    // 基于用户ID和服务器密钥生成
    return crypto
        .createHmac('sha256', serverSecret)
        .update(userId.toString())
        .digest('hex')
        .substring(0, 32); // AES-256需要32字符
}

// 用户登录/注册
router.post('/login', [
    body('openid').notEmpty().withMessage('openid不能为空'),
    body('userInfo').isObject().withMessage('用户信息格式错误')
], async (req, res) => {
    try {
        // 验证输入
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                message: '输入验证失败',
                errors: errors.array()
            });
        }

        const { openid, userInfo } = req.body;
        const secretKey = req.headers['x-encryption-key'] || 'default-key';
        const ipAddress = req.ip || req.connection.remoteAddress;

        // 查找或创建用户
        let user = await User.findByOpenid(openid);

        if (!user) {
            // 创建新用户
            await User.create({ openid, userInfo, secretKey });
            user = await User.findByOpenid(openid);

            // 记录注册日志
            await User.logOperation(user.id, 'register', { userInfo }, ipAddress);
        } else {
            // 更新现有用户信息
            await User.update(openid, userInfo, secretKey);

            // 记录登录日志
            await User.logOperation(user.id, 'login', { userInfo }, ipAddress);
        }

        // 生成访问令牌
        const token = generateToken(openid);

        res.json({
            success: true,
            message: '登录成功',
            data: {
                token,
                user: {
                    id: user.id,
                    openid: user.openid,
                    nickname: user.nickname,
                    avatarUrl: user.avatar_url
                }
            }
        });

    } catch (error) {
        console.error('用户登录失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

// 获取用户信息
router.get('/profile', authenticateToken, validateUser, async (req, res) => {
    try {
        const user = await User.findByOpenid(req.user.openid);
        const secretKey = req.headers['x-encryption-key'] || 'default-key';

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 解密用户数据
        let decryptedData = {};
        if (user.encrypted_data) {
            try {
                decryptedData = cryptoUtil.decryptObject(user.encrypted_data, secretKey);
            } catch (error) {
                console.error('解密用户数据失败:', error);
            }
        }

        res.json({
            success: true,
            data: {
                user: {
                    id: user.id,
                    openid: user.openid,
                    nickname: user.nickname,
                    avatarUrl: user.avatar_url,
                    decryptedData,
                    lastLogin: user.last_login,
                    createdAt: user.created_at
                }
            }
        });

    } catch (error) {
        console.error('获取用户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

// 更新用户信息
router.put('/profile', [
    authenticateToken,
    validateUser,
    body('userInfo').isObject().withMessage('用户信息格式错误')
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                message: '输入验证失败',
                errors: errors.array()
            });
        }

        const { userInfo } = req.body;
        const secretKey = req.headers['x-encryption-key'] || 'default-key';
        const ipAddress = req.ip || req.connection.remoteAddress;

        await User.update(req.user.openid, userInfo, secretKey);

        // 记录更新日志
        await User.logOperation(req.user.id, 'update_profile', { userInfo }, ipAddress);

        res.json({
            success: true,
            message: '用户信息更新成功'
        });

    } catch (error) {
        console.error('更新用户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

// 保存隐私数据
router.post('/privacy-data', [
    authenticateToken,
    validateUser,
    body('dataType').notEmpty().withMessage('数据类型不能为空'),
    body('content').notEmpty().withMessage('内容不能为空')
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                message: '输入验证失败',
                errors: errors.array()
            });
        }

        const { dataType, content } = req.body;
        const secretKey = req.headers['x-encryption-key'] || 'default-key';
        const ipAddress = req.ip || req.connection.remoteAddress;

        await User.savePrivacyData(req.user.id, dataType, content, secretKey);

        // 记录保存日志
        await User.logOperation(req.user.id, 'save_privacy_data', { dataType }, ipAddress);

        res.json({
            success: true,
            message: '隐私数据保存成功'
        });

    } catch (error) {
        console.error('保存隐私数据失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

// 获取隐私数据
router.get('/privacy-data/:dataType', authenticateToken, validateUser, async (req, res) => {
    try {
        const { dataType } = req.params;
        const secretKey = req.headers['x-encryption-key'] || 'default-key';

        const data = await User.getPrivacyData(req.user.id, dataType, secretKey);

        if (!data) {
            return res.status(404).json({
                success: false,
                message: '未找到相关数据'
            });
        }

        res.json({
            success: true,
            data: {
                dataType: data.data_type,
                content: data.decrypted_content,
                createdAt: data.created_at,
                updatedAt: data.updated_at
            }
        });

    } catch (error) {
        console.error('获取隐私数据失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

// 删除用户账户
router.delete('/account', authenticateToken, validateUser, async (req, res) => {
    try {
        const ipAddress = req.ip || req.connection.remoteAddress;

        // 记录删除日志
        await User.logOperation(req.user.id, 'delete_account', {}, ipAddress);

        // 软删除用户
        await User.delete(req.user.openid);

        res.json({
            success: true,
            message: '账户删除成功'
        });

    } catch (error) {
        console.error('删除账户失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

module.exports = router;